package frame

import (
	"time"

	"gitee.com/go-mao/mao/libs/crontab"
	"gitee.com/go-mao/mao/libs/try"
)

type crontabDomain struct {
	cronTask *crontab.CronSchduler
	server   *Server
}

// 初始化定时任务
func (this *crontabDomain) init(module ModuleInterface) {
	if this.cronTask == nil {
		this.cronTask = crontab.New()
	}
	taskList := module.Crontabs()
	for _, task := range taskList {
		taskClone := task
		call := func() {
			tl := this.server.TaskLine()
			try.Do(func() {
				this.server.logger.Debugf("[CRON] %s [%d] %s", time.Now().Format("2006-01-02 15:04:05"), tl.index, taskClone.Name())
				taskClone.Handler(tl)
			}, func(e try.Exception) {
				this.server.logger.Errorf("[CRON] %s [%d] [%s] [%d]  %s", time.Now().Format("2006-01-02 15:04:05"), tl.index, taskClone.Name(), e.ErrCode(), e.ErrMsg())
			})
		}
		job, err := crontab.NewJobModel(taskClone.Schedule(), call)
		if err != nil {
			try.Throw(CODE_FATAL, "定时任务【"+taskClone.Name()+"】错误：", err.Error())
		}
		this.cronTask.DynamicRegister(taskClone.Name(), job)
	}
}
